//
//  GYChooseView.m
//  GYDemo
//
//  Created by Mrzhang on 2018/3/27.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "GYChooseView.h"
#import "Head.h"
#import "GYProductCateModel.h"
#import "GYCategoryPickerView.h"
@interface GYChooseView ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong)UIButton* leftbtn;
@property(nonatomic,strong)UIImageView* leftIV;
@property(nonatomic,strong)UIButton* orderbtn;
@property(nonatomic,strong)UIImageView* orderIV;
@property(nonatomic,strong)UIView* displayView;
@property(nonatomic,strong)UILabel* countLab;
@property(nonatomic,strong)GCBaseTableView* chooseTable;
@property(nonatomic,assign)BOOL cellType;
@property(nonatomic,assign)float tableHeight;
@property(nonatomic,assign)ChooseViewType selectType;
@property(nonatomic,strong)NSMutableArray* orderArr;
@property(nonatomic,assign)float orginLength;
@property(nonatomic,strong)NSMutableDictionary* paraDic;
@property(nonatomic,strong)NSMutableArray* pickViewArr;
@property(nonatomic,strong)NSMutableArray* storageTypeData;
@property(nonatomic,strong)NSMutableArray* storageSupplyData;
@property(nonatomic,strong)NSMutableArray* storageAreaData;
@end

@implementation GYChooseView
-(NSMutableArray *)pickViewArr
{
    if (!_pickViewArr) {
        _pickViewArr=[NSMutableArray new];
    }
    return _pickViewArr;
}
-(NSMutableArray *)storageAreaData
{
    if (!_storageAreaData) {
        _storageAreaData=[[NSMutableArray alloc] init];
    }
    return _storageAreaData;
}
-(NSMutableArray *)storageTypeData
{
    if (!_storageTypeData) {
        _storageTypeData=[[NSMutableArray alloc] init];
    }
    return _storageTypeData;
}
-(NSMutableArray *)storageSupplyData
{
    if (!_storageSupplyData) {
        _storageSupplyData=[[NSMutableArray alloc] init];
    }
    return _storageSupplyData;
}
-(NSMutableDictionary *)paraDic
{
    if (!_paraDic) {
        _paraDic=[[NSMutableDictionary alloc] init];
    }
    return _paraDic;
}
-(NSMutableArray *)orderArr
{
    if (!_orderArr) {
        _orderArr=[[NSMutableArray alloc] initWithObjects:@"综合排序",@"价格",@"成交量", nil];
    }
    return _orderArr;
}
-(ChooseViewType)selectType
{
    if (!_selectType) {
        _selectType=ChooseViewTypeAll;
    }
    return _selectType;
}
-(UIButton *)leftbtn{
    if (!_leftbtn) {
        _leftbtn=[UIButton buttonWithType:UIButtonTypeCustom];
        _leftbtn.frame=WFCGRectMake(8.5, 0, 80, 45);
        [_leftbtn setTitle:@"筛选" forState:UIControlStateNormal];
        [_leftbtn setTitleColor:Main_Color_Red forState:UIControlStateNormal];
        _leftbtn.titleLabel.font=SYSTEMFONT(14);
        [_leftbtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -16, 0, 0)];
        [_leftbtn addTarget:self action:@selector(showView:) forControlEvents:UIControlEventTouchUpInside];
        [_leftbtn addSubview:self.leftIV];

    }
    return _leftbtn;
}
-(UIImageView *)leftIV{
    if (!_leftIV) {
        _leftIV=[[UIImageView alloc] init];
        _leftIV.image=[UIImage imageNamed:@"Triangle"];
        _leftIV.frame=WFCGRectMake(50, (45-_leftIV.image.size.height)/2, _leftIV.image.size.width, _leftIV.image.size.height);
    }
    return _leftIV;
}
-(UIImageView *)orderIV{
    if (!_orderIV) {
        _orderIV=[[UIImageView alloc] init];
        _orderIV.image=[UIImage imageNamed:@"Triangle"];
        _orderIV.frame=WFCGRectMake(55, (45-_orderIV.image.size.height)/2, _orderIV.image.size.width, _orderIV.image.size.height);
    }
    return _orderIV;
}
-(UIButton *)orderbtn{
    if (!_orderbtn) {
        _orderbtn=[UIButton buttonWithType:UIButtonTypeCustom];
        _orderbtn.frame=WFCGRectMake(120, 0, 100, 45);
        [_orderbtn setTitle:@"综合排序" forState:UIControlStateNormal];
        [_orderbtn setTitleColor:Main_Color_Black forState:UIControlStateNormal];
         [_orderbtn setTitleColor:Main_Color_Red forState:UIControlStateSelected];
        [_orderbtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -50, 0, 0)];
        _orderbtn.titleLabel.font=SYSTEMFONT(14);
        [_orderbtn addSubview:self.orderIV];
        [_orderbtn addTarget:self action:@selector(showView:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _orderbtn;
}
-(UIView *)displayView{
    
    if (!_displayView) {
        _displayView=[[UIView alloc] init];
        _displayView.backgroundColor=[UIColor blackColor];
        _displayView.alpha=.3;
        UITapGestureRecognizer* tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(missAllView)];
        tap.numberOfTapsRequired=1;
        [_displayView addGestureRecognizer:tap];
        _displayView.userInteractionEnabled=YES;
        _displayView.y = self.bottom;
        _displayView.width = self.width;
        _displayView.height = WF_UI_VIEW_HEIGHT;
        _displayView.hidden = YES;
    }
    return _displayView;
}
-(GCBaseTableView *)chooseTable
{
    if (!_chooseTable) {
        
        _chooseTable=[[GCBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _chooseTable.frame=WFCGRectMake(0, -45*5, 375, 45*3);
        _chooseTable.dataSource=self;
        _chooseTable.delegate=self;
        [_chooseTable setSeparatorColor: Main_Color_BG];
        _chooseTable.showsVerticalScrollIndicator=NO;
        _chooseTable.scrollEnabled=NO;
    }
    return _chooseTable;
}

-(UILabel *)countLab
{
    if (!_countLab) {
        _countLab=[[UILabel alloc] init];
        _countLab.textColor=Main_Color_LightGray;
        _countLab.font=SYSTEMFONT(12);
        _countLab.textAlignment=NSTextAlignmentRight;
        _countLab.frame=WFCGRectMake(375-110, 0, 100, 45);
        
    }
    return _countLab;
}

-(instancetype)initWithFrame:(CGRect)frame chooseViewType:(ChooseViewType)type
{
    self=[super initWithFrame:frame];
    if (self)
    {
        _selectType=type;
        _tableHeight=45*4;
        _orginLength=0;
        if (type==ChooseViewTypeAllNoRegin||type==ChooseViewTypeSingle||type==ChooseViewTypeSingleCenter)
        {
            _tableHeight=45*3;
        }
        if (type==ChooseViewTypeStorage) {
            _tableHeight=45*5;
        }
        self.chooseTable.height=WFCGFloatY(_tableHeight);
        
        [self addSubview:self.leftbtn];
        [self addSubview:self.orderbtn];
        [self addSubview:self.countLab];
        if (type==ChooseViewTypeStorage)
        {
            [self requestType:@"15"];
            [self requestType:@"16"];
            [self requestType:@"17"];
        }else
        {
            [self requestCategory];
        }
        
    }
    return self;
}
-(void)setListFrame:(float)leftOrigin
{
    _orginLength=leftOrigin;
}
-(void)setTotalCount:(NSString *)count
{
     self.countLab.text=[NSString stringWithFormat:@"总共有%@件产品",count];
}
-(void)layoutSubviews
{
    [super layoutSubviews];
    [self.superview addSubview:self.displayView];
    [self.superview addSubview:self.chooseTable];
//    [self.superview insertSubview:self.displayView belowSubview:self];
//    [self.superview insertSubview:self.chooseTable belowSubview:self];
    [self.superview bringSubviewToFront:self];
    switch (_selectType) {
        case ChooseViewTypeSingle:
        {
            [self.orderbtn setHidden:YES];
        }
            break;
        case ChooseViewTypeSingleCenter:
        {
            [self.orderbtn setHidden:YES];
        }
            break;
        case ChooseViewTypeStorage:
        {
            [self.orderbtn setHidden:YES];
        }
            break;
            
        default:
            break;
    }
}
-(void)showView:(UIButton*)sender
{
//    _displayView.frame=WFCGRectMake(0, 45, 375, GY_View_Height_Nav);
    _displayView.hidden = NO;
    _displayView.x=_orginLength;
    if (sender==_leftbtn) {
        _cellType=0;
        [UIView animateWithDuration:0.3 animations:^{
            _orderbtn.selected=NO;
            _leftIV.transform=CGAffineTransformMakeRotation(M_PI);
            _orderIV.transform=CGAffineTransformMakeRotation(0);
        }];
        _chooseTable.y = WFCGFloatY(45);
        _chooseTable.x=_orginLength;
        _chooseTable.height = WFCGFloatY(_tableHeight);
    }else
    {
        _cellType=1;
        [UIView animateWithDuration:0.3 animations:^{
            _orderbtn.selected=YES;
            _leftIV.transform=CGAffineTransformMakeRotation(0);
            _orderIV.transform=CGAffineTransformMakeRotation(M_PI);
        }];
        _chooseTable.y = WFCGFloatY(45);
        _chooseTable.x=_orginLength;
        _chooseTable.height = WFCGFloatY(45*3);
    }
    CATransition *transition = [CATransition animation];
    transition.type = kCATransitionMoveIn;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.fillMode = kCAFillModeForwards;
    transition.duration = 0.3;
    transition.subtype = kCATransitionFromBottom;
    [[_chooseTable layer] addAnimation:transition forKey:@"UITableViewReloadDataAnimationKey"];
    [_chooseTable reloadData];
}
-(void)missAllView
{
    _orderbtn.selected=NO;
    [self endEditing:YES];
    [UIView animateWithDuration:0.3 animations:^{
        _leftIV.transform=CGAffineTransformMakeRotation(0);
        _orderIV.transform=CGAffineTransformMakeRotation(0);
        _chooseTable.y = self.y - _chooseTable.height;
        _chooseTable.x=_orginLength;
    } completion:^(BOOL finished) {
        _displayView.hidden = YES;
    }];
}

-(void)finishBtnPress
{
    [self missAllView];
    if (_cellType==0)
    {
        
        for (NSString* key in self.paraDic.allKeys)
        {
            if ([key hasSuffix:@"name"])
            {
                [self.paraDic removeObjectForKey:key];
            }
        }
        
        _chooseBack(self.paraDic);
    }else
    {
        _categoryback(@"");
    }
    [self.paraDic removeAllObjects];
}
#pragma mark - delegate
#pragma mark - table delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_selectType==ChooseViewTypeAll) {
        if (_cellType==0)
        {
            return 4;
        }
        return 3;
    }
    
    if (_selectType==ChooseViewTypeStorage) {
        return 5;
    }
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"section2cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    [cell.contentView removeAllSubviews];
    NSArray* arr;
    
    UILabel* leftlab=[[UILabel alloc] init];
    leftlab.textAlignment=NSTextAlignmentLeft;
    leftlab.textColor=Main_Color_Black;
    leftlab.font=SYSTEMFONT(14);
    leftlab.frame=WFCGRectMake(10, 0, 70, 45);
    [cell.contentView addSubview:leftlab];
    
    UITextField* inputTx=[[UITextField alloc] init];
    inputTx.font=SYSTEMFONT(14);
    inputTx.textColor=Main_Color_Black;
    inputTx.frame=WFCGRectMake(90, 0, 375-95, 45);
    [cell.contentView addSubview:inputTx];
    [inputTx setAdjustsFontSizeToFitWidth:YES];
    inputTx.enabled=NO;
    inputTx.delegate=self;
    
    if (_cellType==1) {
        inputTx.hidden=YES;
        leftlab.frame=WFCGRectMake(0, 0, 375, 45);
        leftlab.textAlignment=NSTextAlignmentCenter;
        leftlab.text=self.orderArr[indexPath.row];
    }else
    {
        if (_selectType==ChooseViewTypeAll)
        {
            arr=@[@"地区",@"品名",@"产品种类",@"完成"];
            if (indexPath.row==3)
            {
                leftlab.frame=WFCGRectMake(0, 0, 375, 45);
                leftlab.textAlignment=NSTextAlignmentCenter;
                leftlab.textColor=Main_Color_Blue;
            }
            if (indexPath.row==1)
            {
                inputTx.enabled=YES;
            }
            
            if (indexPath.row==0) {
                inputTx.text=[NSString stringWithFormat:@"%@ %@ %@",_paraDic[@"provincename"]?:@"",_paraDic[@"cityname"]?:@"",_paraDic[@"areaname"]?:@""];
            }
            if (indexPath.row==2)
            {
                inputTx.text=[NSString stringWithFormat:@"%@",_paraDic[@"protypename"]?:@""];
            }
            if (indexPath.row==1)
            {
                inputTx.text=[NSString stringWithFormat:@"%@",_paraDic[@"keyword"]?:@""];
            }
            
        }else if (_selectType==ChooseViewTypeStorage)
        {
            arr=@[@"地区",@"面积",@"供应",@"类型",@"完成"];
            if (indexPath.row==4)
            {
                leftlab.frame=WFCGRectMake(0, 0, 375, 45);
                leftlab.textAlignment=NSTextAlignmentCenter;
                leftlab.textColor=Main_Color_Blue;
            }
            
            if (indexPath.row==0) {
                inputTx.text=[NSString stringWithFormat:@"%@ %@ %@",_paraDic[@"provincename"]?:@"",_paraDic[@"cityname"]?:@"",_paraDic[@"areaname"]?:@""];
            }
            if (indexPath.row==1)
            {
                inputTx.text=[NSString stringWithFormat:@"%@",_paraDic[@"acreagename"]?:@""];
            }
            if (indexPath.row==2)
            {
                inputTx.text=[NSString stringWithFormat:@"%@",_paraDic[@"supplyname"]?:@""];
            }
            if (indexPath.row==3)
            {
                inputTx.text=[NSString stringWithFormat:@"%@",_paraDic[@"typename"]?:@""];
            }
        }else
        {
            arr=@[@"品名",@"产品种类",@"完成"];
            if (indexPath.row==2)
            {
                leftlab.frame=WFCGRectMake(0, 0, 375, 45);
                leftlab.textAlignment=NSTextAlignmentCenter;
                leftlab.textColor=Main_Color_Blue;
            }
            if (indexPath.row==0)
            {
                inputTx.enabled=YES;
            }
            
            if (indexPath.row==1)
            {
                inputTx.text=[NSString stringWithFormat:@"%@",_paraDic[@"protypename"]?:@""];
            }
            if (indexPath.row==0)
            {
                inputTx.text=[NSString stringWithFormat:@"%@",_paraDic[@"keyword"]?:@""];
            }
        }
        leftlab.text=arr[indexPath.row];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return WFCGFloatY(45);
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.001f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_cellType==1) {
        [self missAllView];
        [_orderbtn setTitle:self.orderArr[indexPath.row] forState:UIControlStateNormal];
        NSString* str;
        switch (indexPath.row) {
            case 0:
                str=@"1";
                break;
            case 1:
                str=@"2";
                break;
            case 2:
                str=@"4";
                break;
                
            default:
                break;
        }
        _categoryback(str);
    }else
    {
        if (_selectType==ChooseViewTypeAll)
        {
            if (indexPath.row==0)
            {
                
                [BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeArea dataSource:[WFFunctions getLocalAddressList] defaultSelected:nil isAutoSelect:nil themeColor:Main_Color_Black resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
                    
                    self.paraDic[@"province"]=[WFFunctions replaceZerofromStr:province.code];
                    self.paraDic[@"provincename"]=province.name;
                    self.paraDic[@"city"]=[WFFunctions replaceZerofromStr:city.code];
                    self.paraDic[@"cityname"]=city.name;
                    self.paraDic[@"area"]=[WFFunctions replaceZerofromStr:area.code];
                    self.paraDic[@"areaname"]=area.name;
                    [self.chooseTable reloadData];
                    
                } cancelBlock:^{
                    
                }];
                
            }
            if (indexPath.row==2)
            {
                [GYCategoryPickerView showAddressPickerWithShowType:BRAddressPickerModeArea dataSource:nil defaultSelected:nil isAutoSelect:NO themeColor:Main_Color_Black resultBlock:^(FirstCategoryModel *province, SecondCategoryModel *city, ThirdCategoryModel *area) {
                    self.paraDic[@"protypeid"]=[WFFunctions replaceZerofromStr:area.code];
                    self.paraDic[@"protypename"]=area.name;
                    [self.chooseTable reloadData];
                } cancelBlock:^{
                    
                }];
            }
            if (indexPath.row==3) {
                [self finishBtnPress];
            }
        }
        
        if (_selectType==ChooseViewTypeAllNoRegin||_selectType==ChooseViewTypeSingle||_selectType==ChooseViewTypeSingleCenter)
        {
            if (indexPath.row==1)
            {
                [GYCategoryPickerView showAddressPickerWithShowType:BRAddressPickerModeArea dataSource:nil defaultSelected:nil isAutoSelect:NO themeColor:Main_Color_Black resultBlock:^(FirstCategoryModel *province, SecondCategoryModel *city, ThirdCategoryModel *area) {
                    self.paraDic[@"protypeid"]=[WFFunctions replaceZerofromStr:area.code];
                    self.paraDic[@"protypename"]=area.name;
                    [self.chooseTable reloadData];
                } cancelBlock:^{
                    
                }];
            }
            if (indexPath.row==2) {
                [self finishBtnPress];
            }
        }
        
        if (_selectType==ChooseViewTypeStorage)
        {
            if (indexPath.row==0)
            {
                
                [BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeArea dataSource:[WFFunctions getLocalAddressList] defaultSelected:nil isAutoSelect:nil themeColor:Main_Color_Black resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
                    
                    self.paraDic[@"province"]=[WFFunctions replaceZerofromStr:province.code];
                    self.paraDic[@"provincename"]=province.name;
                    self.paraDic[@"city"]=[WFFunctions replaceZerofromStr:city.code];
                    self.paraDic[@"cityname"]=city.name;
                    self.paraDic[@"area"]=[WFFunctions replaceZerofromStr:area.code];
                    self.paraDic[@"areaname"]=area.name;
                    [self.chooseTable reloadData];
                    
                } cancelBlock:^{
                    
                }];
                

            }else if (indexPath.row==4)
            {
                [self finishBtnPress];
            }
            else
            {
                NSMutableArray* arr=[[NSMutableArray alloc] init];
                if (indexPath.row==1)
                {
                    for (NSDictionary* dic in self.storageAreaData)
                    {
                        NSMutableString* myst=[[NSMutableString alloc] initWithString:[dic objectForKey:@"name"]];
                         [arr addObject:myst];
                    }
                }
                if (indexPath.row==2)
                {
                    for (NSDictionary* dic in self.storageSupplyData)
                    {
                        [arr addObject:dic[@"name"]];
                    }
                }
                if (indexPath.row==3)
                {
                    for (NSDictionary* dic in self.storageTypeData)
                    {
                        [arr addObject:dic[@"name"]];
                    }
                }
                
                [BRStringPickerView showStringPickerWithTitle:indexPath.row==1?@"面积":indexPath.row==2?@"供应":@"类型" dataSource:arr defaultSelValue:nil resultBlock:^(id selectValue) {
                    
                    if (indexPath.row==1)
                    {
                        for (NSDictionary* dic in self.storageAreaData)
                        {
                            if ([dic[@"name"] isEqualToString:selectValue])
                            {
                                self.paraDic[@"acreage"]=[dic objectForKey:@"id"];
                            }
                        }
                        self.paraDic[@"acreagename"]=selectValue;
                    }
                    
                    if (indexPath.row==2)
                    {
                        for (NSDictionary* dic in self.storageSupplyData)
                        {
                            if ([dic[@"name"] isEqualToString:selectValue])
                            {
                                self.paraDic[@"supply"]=[dic objectForKey:@"id"];
                            }
                        }
                        self.paraDic[@"supplyname"]=selectValue;
                    }
                    
                    if (indexPath.row==3)
                    {
                        for (NSDictionary* dic in self.storageTypeData)
                        {
                            if ([dic[@"name"] isEqualToString:selectValue])
                            {
                                self.paraDic[@"type"]=[dic objectForKey:@"id"];
                            }
                        }
                        self.paraDic[@"typename"]=selectValue;
                    }
                     [self.chooseTable reloadData];
                }];
            }

        }
    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString* str=[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.paraDic[@"keyword"]=str;
}

-(void)requestCategory
{
    NSMutableDictionary *para = [[NSMutableDictionary alloc]init];
    NSString *inter = @"productCategory";
    [[InterfaceManager shareInterface]requetInterface:inter withParameter:para handler:^(NSDictionary *info,InterfaceStatusModel *infoModel) {
        NSArray *data = [infoModel.data objectForKey:@"list"];

        self.pickViewArr=[[NSMutableArray alloc] initWithArray:data];

    }];
}

-(void)requestType:(NSString*)typeid
{
    NSMutableDictionary *para = [[NSMutableDictionary alloc]init];
    [para setObject:typeid forKey:@"type"];
    NSString *inter = @"storageType";
    [[InterfaceManager shareInterface]requetInterface:inter withParameter:para handler:^(NSDictionary *info,InterfaceStatusModel *infoModel) {
        NSArray *data = infoModel.data;
        if ([typeid isEqualToString:@"15"])
        {
            self.storageTypeData=[[NSMutableArray alloc] initWithArray:data];
        }
        if ([typeid isEqualToString:@"16"])
        {
            self.storageSupplyData=[[NSMutableArray alloc] initWithArray:data];
        }
        if ([typeid isEqualToString:@"17"])
        {
            self.storageAreaData=[[NSMutableArray alloc] initWithArray:data];
        }
       
        
    }];
}


@end
